package com.wz.project.util;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

//import com.sap.me.frame.BasicBOBeanException;
//import com.sap.me.frame.Data;

/**
 * @author zhihao.sang
 * @Description: restful请求工具类
 * @date 2020年6月25日 上午11:14:31
 */
public class HttpClientUtility {

    /**
     * @Description: 发送带json参数、Header的post请求至ThingWorx
     * @param url
     * @param jsonString
     * @param paramHeader
     * @return
     * @throws IOException
     * @throws BasicBOBeanException
     */
//    public static String thingWorxPost(String url, String jsonString, Map<String, String> paramHeader) throws IOException, BasicBOBeanException {
//        // 创建请求客户端
//        CloseableHttpClient httpClient = HttpClients.custom().build();
//        // 创建post请求
//        HttpPost httpPost = new HttpPost(url);
//        // 设置header信息
//        setHeader(httpPost, paramHeader);
//        // 设置JSON数据
//        StringEntity entityStr = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
//        httpPost.setEntity(entityStr);
//        // 设置连接超时时间：15秒
//        httpPost.setConfig(RequestConfig.custom().setConnectTimeout(15000).build());
//        // 执行并获取返回
//        CloseableHttpResponse response = httpClient.execute(httpPost);
//        HttpEntity entity = response.getEntity();
//        String resp = EntityUtils.toString(entity, StandardCharsets.UTF_8);
//        EntityUtils.consume(entity);
//        // 关闭连接
//        response.close();
//        if (response.getStatusLine().getStatusCode() != 200) {
//            // 20226.simple = 调用Thingworx接口失败：%MESSAGE%
//            throw new BasicBOBeanException(20226, new Data("MESSAGE", resp));
//        }
//        return resp;
//    }

    /**
     * @Description: 请求头赋值
     * @param request
     * @param paramHeader
     */
    private static void setHeader(HttpRequestBase request, Map<String, String> paramHeader) {
        // 设置Header
        if (paramHeader != null) {
            paramHeader.forEach(request::addHeader);
        }
    }
    

    /**
     * 
     * @Description: 带权限的请求
     * @param url
     * @param jsonString
     * @param paramHeader
     * @param userName
     * @param password
     * @return
     * @throws IOException
     */
    public static String sendPost(String url, String jsonString, Map<String, String> paramHeader, String userName, String password) throws IOException {
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userName, password);
        provider.setCredentials(AuthScope.ANY, credentials);
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(provider).build();
        String resp = "";
        HttpPost httpPost = new HttpPost(url);
        setHeader(httpPost, paramHeader);
        StringEntity entityStr = new StringEntity(jsonString, ContentType.create("text/plain", "UTF-8"));
        httpPost.setEntity(entityStr);
        CloseableHttpResponse response = null;
        response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        resp = EntityUtils.toString(entity, "UTF-8");
        EntityUtils.consume(entity);
        response.close();
        if (resp == null || resp.equals("")) {
            return "";
        }
        return resp;
    }

    /**
     * 
     * @Description: 发送带json参数、Header的post请求
     * @param url
     * @param jsonString
     * @param paramHeader
     * @return
     * @throws IOException
     */
    public static String sendPost(String url, String jsonString, Map<String, String> paramHeader) throws IOException {
        if (jsonString == null || jsonString.isEmpty()) {
            return sendPost(url, paramHeader);
        }
        String resp = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Authorization",paramHeader.get("Authorization"));
        setHeader(httpPost, paramHeader);
        StringEntity entityStr = new StringEntity(jsonString, ContentType.create("application/json", "UTF-8"));
        httpPost.setEntity(entityStr);
        CloseableHttpResponse response = null;
        response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        resp = EntityUtils.toString(entity, "UTF-8");
        EntityUtils.consume(entity);
        response.close();
        if (resp == null || resp.equals("")) {
            return "";
        }
        return resp;
    }

    /**
     * 
     * @Description: 发送带Header的HttpPost请求
     * @param url
     * @param paramHeader
     * @return
     * @throws IOException
     */
    public static String sendPost(String url, Map<String, String> paramHeader) throws IOException {
        // 1.获得一个httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 2.生成一个post请求
        HttpPost httpPost = new HttpPost(url);
       // setHeader(httpPost, paramHeader);
        CloseableHttpResponse response = null;
        //创建参数列表
        if(paramHeader!=null){
            List<NameValuePair> paramValueList = new ArrayList<NameValuePair>();
            for (String key : paramHeader.keySet()) {
                Object value = paramHeader.get(key);
                if(value!=null){
                    paramValueList.add(new NameValuePair() {
                        
                        @Override
                        public String getValue() {
                            return value + "";
                        }
                        
                        @Override
                        public String getName() {
                            return key;
                        }
                    });
                    
                }
            }
            //模拟表单
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramValueList, "UTF-8");
            httpPost.setEntity(entity);
        }
        // 3.执行post请求并返回结果
        response = httpclient.execute(httpPost);
        // 4.处理结果，这里将结果返回为字符串
        HttpEntity entity = response.getEntity();
        String result = null;
        result = EntityUtils.toString(entity);
        return result;
    }

    public static String doGet(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }


}
